import { Component } from "react";
import Taro from "@tarojs/taro";
import Utils from "../../../utils/index";
import { View, ScrollView, Image } from "@tarojs/components";
import LgTarBarItem from "../tarBarItem";
// import {AtSwitch, AtForm} from 'taro-ui'

import "../../images/public/style.css";
import "./index.scss";

import warnPng from "./images/warn.png";

/*
    参数说明
    传入：{
        className,//可选 备注：父容器className便于修改背景颜色，阴影等
        imageUrl,//可选 备注：不传默认使用默认占位图
        selectedImageUrl, //可选 备注：不传默认使用imageUrl，若也无imageUrl默认占位图
        name, //可选 备注：不传默认为“标题X”
        selectedName, //已剔除
        selectedNameColor,//可选 备注：默认颜色rgb(0,144,255)
        defaultSelectedIndex,//可选 备注：默认0
    }
    提供回调事件：{
        handleChange(index)//index为点击当前点击索引index
    }
*/

export default class LgFloorNav extends Component {
  constructor() {
    super(...arguments);
    this.triggerState = this.triggerState.bind(this);
    this.onScrolling = this.onScrolling.bind(this);
    this.onScrollToUpper = this.onScrollToUpper.bind(this);
    this.onScrollToLower = this.onScrollToLower.bind(this);
    this.handToBottom = this.handToBottom.bind(this);
  }
  state = {
    lists: [],
    scrollToId: "",
    unikey: 0,
    // posiX: Taro.pxTransform(26),
    // posiY: Taro.pxTransform(50),
    posiX: 26,
    posiY: 50,
  };
  //滚动事件
  updateScrollToId(scrollToId = "") {
    this.setState({ scrollToId: scrollToId });
  }
  onScrolling(e) {
    // const { scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY } = e.detail
    this.updateScrollToId("");
  }
  onScrollToUpper() {
    this.updateScrollToId("");
  }
  onScrollToLower() {
    this.updateScrollToId("nav_item_all");
  }
  handToBottom() {
    this.updateScrollToId("nav_item_all");
  }

  triggerState(index) {
    let lists = this.state.lists;
    lists = lists.map((o) => {
      return {
        ...o,
        isSelected: false,
      };
    });
    lists[index].isSelected = true;
    this.setState({ lists });
    this.props.handleChange && this.props.handleChange(lists[index].index);
  }
  move(x, y) {
    let posiX = x,
      posiY = y;
    if (posiX < 10) {
      posiX = 10;
    } else if (posiX > this.windowWidth - this.navDomWidth - 10) {
      posiX = this.windowWidth - this.navDomWidth - 10;
    }
    if (posiY < 10) {
      posiY = 10;
    } else if (posiY > this.windowHeight - this.navDomHei - 10) {
      posiY = this.windowHeight - this.navDomHei - 10;
    }
    this.setState({ posiX, posiY });
  }
  onTouchDown = (e) => {
    // console.log(e)
    let { pageX, pageY } = e.changedTouches[0];
    this.startPoint.x = pageX;
    this.startPoint.y = pageY;
  };
  onTouchMove = (e) => {
    e.preventDefault(); //阻止默认行为（滚动条滚动）
    e.stopPropagation();
    this.isTouchMove = true;
    let { pageX, pageY } = e.changedTouches[0];
    let diffPoint = {}; //要移动的距离
    let movePoint = {
      //移动之后的距离
      x: 0,
      y: 0,
    };

    diffPoint.x = pageX - this.startPoint.x;
    diffPoint.y = pageY - this.startPoint.y;

    movePoint.x = diffPoint.x + this.curPoint.x; //移动之后的距离=要移动的距离+当前距离
    movePoint.y = diffPoint.y + this.curPoint.y;
    // if(options.x){
    //     movePoint.x=diffPoint.x+this.curPoint.x;//移动之后的距离=要移动的距离+当前距离
    // }
    // if(options.y){
    //     movePoint.y=diffPoint.y+this.curPoint.y;
    // }

    this.move(movePoint.x, movePoint.y);
  };
  onTouchUp = (e) => {
    if (!this.isTouchMove) return;
    let { pageX, pageY } = e.changedTouches[0];
    this.curPoint.x += pageX - this.startPoint.x; //更新当前位置
    this.curPoint.y += pageY - this.startPoint.y;

    this.isTouchMove = false;
  };
  onTouchCancel = (e) => {
    // console.log('onTouchCancel,',e)
  };
  transformToPx = (size) => {
    var transSize = 0;
    var width = this.windowWidth;
    if (process.env.TARO_ENV === "weapp") {
      transSize = size * (width / 750);
    } else {
      //if (process.env.TARO_ENV === 'h5')
      if (width >= 640) {
        var baseSize = 40;
      } else if (width <= 320) {
        var baseSize = 20;
      } else {
        var baseSize = (width / 320) * 20;
      }
      transSize =
        Math.ceil(parseFloat(Taro.pxTransform(size)) * baseSize * 10000) /
        10000;
    }
    return transSize;
  };
  initData(data) {
    let lists = data;
    let timestamp = new Date().getTime();
    lists = lists.map((o, i) => {
      if (this.props.showAttr) {
        return {
          ...o,
          index: i,
          isSelected: false,
          scrollToId: "nav_item_" + i,
        };
      } else {
        return {
          title: o,
          index: i,
          isSelected: false,
          scrollToId: "nav_item_" + i,
        };
      }
    });
    //添加 全部 项
    lists.push("全部");
    lists[lists.length - 1] = {};
    lists[lists.length - 1][this.props.showAttr || "title"] = "全部";
    lists[lists.length - 1]["index"] = -1;
    lists[lists.length - 1]["isSelected"] = true;
    lists[lists.length - 1]["scrollToId"] = "nav_item_all"; //点击下箭头滚动使用
    this.setState({ lists, unikey: timestamp });
    setTimeout(() => {
      this.setState({ scrollToId: "nav_item_all" });
    }, 100);
  }
  UNSAFE_componentWillReceiveProps(np) {
    if (np.lists.length != this.props.lists.length) {
      this.initData(np.lists);
    }
  }
  componentDidMount() {
    let that = this;
    Taro.getSystemInfo({
      success(res) {
        that.windowWidth = res.windowWidth;
        that.windowHeight = res.windowHeight;
        that.navDomWidth = that.transformToPx(80);
        that.navDomHei = that.transformToPx(350);
        that.curPoint = {
          x: 10,
          y: res.windowHeight - that.navDomHei - 10,
        };
        that.startPoint = {};
        that.isTouchMove = false;
        that.setState({ posiX: that.curPoint.x, posiY: that.curPoint.y });
      },
    });
    this.initData(this.props.lists || []);
  }
  render() {
    const lists = this.state.lists || [],
      className = this.props.className ? " " + this.props.className : "",
      attr = this.props.showAttr || "title";
    let navContHeight = Taro.pxTransform(75 + 75 * 3); //大于3层楼默认高度
    if (lists.length <= 3) {
      navContHeight = Taro.pxTransform(75 + 75 * lists.length); //小于三层楼的实际高度
    }
    let navSty = { height: navContHeight };
    //滚动
    let scrollToId = this.state.scrollToId,
      dragSty = { left: this.state.posiX + "px", top: this.state.posiY + "px" },
      unikey = this.state.unikey;
    // flagImg
    return (
      <View style={dragSty} className={"nav_container" + className}>
        <View
          className="nav_up"
          onTouchStart={this.onTouchDown}
          onTouchMove={this.onTouchMove}
          onTouchEnd={this.onTouchUp}
          onTouchCancel={this.onTouchCancel}
        >
          <View className="nav_triangle"></View>
        </View>
        <ScrollView
          className="nav_cont"
          scrollIntoView={scrollToId}
          onScrollToUpper={this.onScrollToUpper}
          onScrollToLower={this.onScrollToLower}
          lowerThreshold={0}
          onScroll={this.onScrolling}
          style={navSty}
          scrollY={true}
          scrollWithAnimation={true}
        >
          {lists.map((o, i) => {
            return (
              <LgFloorNavItem
                data={o}
                index={i}
                attr={attr}
                key={"nav_item" + unikey + i}
                triggerState={this.triggerState}
              ></LgFloorNavItem>
            );
          })}
        </ScrollView>
        <View
          className="nav_down"
          onClick={this.handToBottom}
          onTouchStart={this.onTouchDown}
          onTouchMove={this.onTouchMove}
          onTouchEnd={this.onTouchUp}
        >
          <View className="nav_triangle"></View>
        </View>
      </View>
    );
  }
}

//楼层item
class LgFloorNavItem extends Component {
  constructor() {
    super(...arguments);
    this.triggerState = this.triggerState.bind(this);
  }
  state = {
    data: {},
  };
  componentDidMount() {
    this.setState({ data: this.props.data });
  }
  UNSAFE_componentWillReceiveProps(np) {
    this.setState({ data: np.data });
  }
  triggerState() {
    this.props.triggerState && this.props.triggerState(this.props.index);
  }
  render() {
    const data = this.state.data,
      attr = this.props.attr || "",
      showTitle = attr ? data[attr] : data || "--",
      isSelected = data.isSelected,
      id = data.scrollToId,
      warn = data.warn || false,
      flagImg = warn ? (data.flagImg || warnPng) : (data.flagImg || '')
    return (
      <View className="nav_item_warp">
        <View
          className={"nav_item oneline" + (isSelected ? " nav_item_cho" : "")}
          onClick={this.triggerState}
          id={id}
        >
          {showTitle}
        </View>
        {
          flagImg ? (
            <Image src={flagImg} mode="aspectFit" className="nav_item_flag"></Image>
          ) : ''
        }
      </View>
    );
  }
}
